Page({
  data: {
    article: {},
    topArticles: []
  },
  onLoad(options) {
    const id = options.id;
    wx.request({
      url: `http://localhost:8080/article/read/${id}`,
      method: 'PUT',
      complete: () => {
        this.getArticleDetail(id);
      }
    });
    this.getTopArticles(id);
  },
  getArticleDetail(id) {
    wx.request({
      url: `http://localhost:8080/article/${id}`,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.code === 200) {
          let raw = res.data.data || {};
          let article = {
            articleName: raw.articleTitle || raw.articleName || '',
            articleTime: raw.createTime || raw.articleTime || '',
            articleReadCount: raw.readCount || raw.articleReadCount || 0,
            articlePic: raw.articlePic && !/^https?:\/\//.test(raw.articlePic) ? 'http://localhost:8080' + raw.articlePic : raw.articlePic,
            articleDes: raw.articleDes || raw.articleDescription || '',
            articleDetails: raw.articleContent || raw.articleDetails || ''
          };
          this.setData({ article });
        } else {
          wx.showToast({ title: '未找到文章', icon: 'none' });
        }
      }
    });
  },
  getTopArticles(currentId) {
    wx.request({
      url: 'http://localhost:8080/article/page',
      method: 'GET',
      data: {
        page: 1,
        pageSize: 10,
        sort: 'articleReadCount,desc'
      },
      success: (res) => {
        if (res.data && res.data.code === 200) {
          let list = res.data.data.list || [];
          list = list.filter(item => item.articleStatus === 1 && item.id != currentId);
          list = list.slice(0, 3).map(raw => ({
            articleName: raw.articleTitle || raw.articleName || '',
            articleDes: raw.articleDes || raw.articleDescription || '',
            articleReadCount: raw.readCount || raw.articleReadCount || 0,
            articlePic: raw.articlePic && !/^https?:\/\//.test(raw.articlePic) ? 'http://localhost:8080' + raw.articlePic : raw.articlePic,
            id: raw.id
          }));
          this.setData({ topArticles: list });
        }
      }
    });
  },
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
})